/*
 * Created on 05.02.2004
 * Local Projects Database
 * Mihai Postelnicu (mihai@ro-gateway.org)
 * (c) 2003 by eRomania Gateway
 */
package ro.gateway.aida.tags;

import java.util.ArrayList;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;

import ro.gateway.aida.db.DBWrapper;
import ro.gateway.aida.db.PersistenceManager;
import ro.gateway.aida.db.PersistenceToken;
import ro.gateway.aida.obj.BreadCrumb;
import ro.xblue.translator.LanguageBean;
import ro.xblue.translator.ShowEditButtonAction;
import ro.xblue.translator.TranslatorConstants;


/**
 * @author Mihai Postelnicu - e-mail (mihai@ro-gateway.org)
 * Creates breadcrumbs for the requested section
 *
 * (c) 2003 by eRomania Gateway<p>
 */
public class BreadCrumbsTag extends BodyTagSupport {
    private ArrayList bcs;

    public int doStartTag() throws JspException {
		   return EVAL_BODY_BUFFERED;
	}

    private BreadCrumb searchBreadCrumb(String label, String lang) {
        Iterator i = bcs.iterator();
		BreadCrumb alter=null;
        //if (!label.equals("bc.home"))
            while (i.hasNext()) {
                BreadCrumb bc = (BreadCrumb) i.next();
				if (bc.getLabel().equals(label)) alter=bc;
                if ((bc.getLabel().equals(label)) && bc.getTrn().getLang().equals(lang))
                    return bc;
            }

        return alter;
    }

    /*
    private BreadCrumb searchBreadCrumb(String name, String lang) {
        Iterator i = bcs.iterator();
		BreadCrumb alter=null;
        while (i.hasNext()) {
            BreadCrumb bc = (BreadCrumb) i.next();
            if(bc.getTrn().getLabel().equals(name)) alter=bc;
            if (bc.getTrn().getLabel().equals(name) &&
                    bc.getTrn().getLang().equals(lang))
                return bc;
        }

        return alter;
    }
*/
    public String showELink(BreadCrumb b, String ctx, boolean show) {
    	if(b.getTrn().getId()==0) return "";
    	if (show) {
        	
            StringBuffer sb = new StringBuffer();
            sb.append("&nbsp;<a class='text' href='");
            sb.append(ctx);
            sb.append("/translator/edit_item.do?action=edit&id=");
            sb.append(b.getTrn().getId());
            sb.append("'>[E]</a>");

            return sb.toString();
        } else return "";
    }

    public String showLink(BreadCrumb b, int k, String ctx) {
		BodyContent bc = bodyContent;
        if (b.getUrl() == null)
            return b.getTrn().getText();
        else {
            StringBuffer sb = new StringBuffer();
            if(k==0) sb.append("<a class='text_searchbold' href='"); else
            sb.append("<a class='text_search' href='");
            sb.append(ctx);
            sb.append(b.getUrl());
            if(bc!=null && bc.getString().trim().length()!=0) sb.append("&key=").append(bc.getString().trim());
            sb.append("'>");
            sb.append(b.getTrn().getText());
            sb.append("</a>");

            return sb.toString();
        }
    }

    public int doEndTag() throws JspException {
        //get context items:
        bcs = (ArrayList) pageContext.getServletContext().getAttribute(BreadCrumb.LIST);
        

        String lang = ((LanguageBean) pageContext.getSession().getAttribute(TranslatorConstants.BLUE_CLANG)).getLanguage();
        HttpServletRequest req = (HttpServletRequest) pageContext.getRequest();
        HttpSession session = req.getSession(true);
        String section = (String) session.getAttribute(BreadCrumb.CURRENT);

        if (section == null)
            section = "bc.home";

        boolean show_links_flag = session.getAttribute(ShowEditButtonAction.FLAG) != null;

		try {
		if(show_links_flag) {
			//i always refresh breadcrumbs while in translator
			PersistenceToken token = PersistenceManager.tokenLookup(pageContext.getServletContext());
			pageContext.getServletContext().setAttribute( BreadCrumb.LIST,
									DBWrapper.getManager( token ).get( new BreadCrumb() ) );
		}

        String ctx = req.getContextPath();
        ArrayList crumbs = new ArrayList();
        Iterator i = bcs.iterator();
        BreadCrumb first = searchBreadCrumb(section, lang);
        crumbs.add(first);

        BreadCrumb current = first;

        while (!current.getLabel().equals("bc.home")) {
            current = searchBreadCrumb(current.getParentLabel(), lang);
            crumbs.add(current);
        }

  
            JspWriter writer = pageContext.getOut();

            for (int k = crumbs.size() - 1; k > -1; k--) {
                BreadCrumb t = (BreadCrumb) crumbs.get(k);
                writer.print(showLink(t,k, ctx) +
                    showELink(t, ctx, show_links_flag));

                if (k != 0)
                    writer.print(" > ");
            }
        } catch (Exception e) {
            System.err.println("BreadCrumbs Exception:" + e);
        }

        return (EVAL_PAGE);
    }

    public static final String LIST = "BreadCrumbsTranslations";

}
